#!/usr/bin/python
# -- coding:utf8 --
import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import pandas as pd
import numpy as np
import pickle


def load_data_from_pickle(file_path_name):
    """
    加载pkl格式数据
    :param file_path_name:
    :return:
    """
    current_path = os.path.dirname(__file__)
    file_path_name = file_path_name.replace("./", current_path + "/")
    file_path_name = file_path_name.replace("\\\\", "/")
    with open(file_path_name, "rb") as infile:
        result = pickle.load(infile)
    return result


def p2score(p, pdo=40, base_score=700):
    """
    概率转换为分数的函数
    说明：概率p=坏的概率
    :param p:
    :param pdo:
    :param base_score:
    :return:
    """
    b = pdo / np.log(2)
    a = base_score + b * np.log(1 / 20)
    if p < 0:
        return -999999
    min_p = 1e-9
    max_p = 1 - min_p
    if p >= max_p:
        p = max_p
    elif p <= min_p:
        p = min_p
    score = int(a + b * np.log((1 - p) / (p)))
    if score < 300:
        return 300
    elif score > 900:
        return 900
    else:
        return score


def get_score(data_df, model_path, model_features_path):
    """
    基于模型结果和入模变量结果计算评分
    :param data_df:
    :param model_path:
    :param model_features_path:
    :return:
    """
    # 特征
    online_model = load_data_from_pickle(model_path)
    feature_cols = load_data_from_pickle(model_features_path)
    # 模型输出概率
    prob = pd.Series(
        online_model.predict_proba(data_df[feature_cols])[:, 1], index=data_df.index
    )
    # 转化打分
    model_score = prob.apply(p2score)
    return model_score


def get_user_model_score_main(features):
    """
    计算评分的主函数
    :param features:
    :return:
    """
    try:
        data_df = pd.DataFrame([features])
        data_df.fillna(-999999, inplace=True)

        # 新客V3版本
        model_path_v4 = './model/new_lgbmmodel_v4.pkl'
        model_features_path_v4 = './model/new_lgbmmodel_fea_v4.pkl'
        creditScoreV4 = get_score(data_df, model_path_v4, model_features_path_v4)[0]

        return {
            'creditScoreV4': creditScoreV4,
        }
    except Exception as e:
        # utils.get_logger().error(e)
        # utils.get_logger().error(features)
        return {
            'creditScoreV4': 0,
        }


if __name__ == "__main__":
    # 新客V2版本测试
    features = {
        'age': 35,
        'appAllbad1InstallIntervalInstallIntervalMax60D': -999999,
        'appAllFuzzyLoanInstallIntervalInstallIntervalMedian60D': -999999,
        'appAllAllInstallIntervalAppNameCnt30D': -999999,
        'smsAllOverdueRemindTimeIntervalMin3D': -999999,
        'smsAllRepayRemindTimeIntervalMax60D': -999999,
        'smsAllOverdueRemindTimeIntervalStd60D': -999999,
        'appAllgood1InstallIntervalInstallIntervalStdAllD': -999999,
        'smsFinancemsgPlatBankTimeIntervalMinAllD': -999999,
        'appIsSystemgood1InstallIntervalInstallIntervalMedian60D': -999999,
        'appAllgood1InstallIntervalInstallIntervalMinAllD': -999999,
        'smsAllAllTimeIntervalStd60D': -999999,
        'appAllAllInstallIntervalInstallIntervalMin3D': -999999,
        'smsAllOverdueRemindTimeIntervalMinAllD': -999999,
        'smsAllVerificationmsgPlatNunique14D': -999999,
        'smsFinanceRepayRemindTimeIntervalMedianAllD': -999999,
        'appAllbad2InstallIntervalInstallIntervalMinAllD': -999999,
        'smsAllOverdueRemindTimeIntervalStdAllD': -999999,
        'appAllbad1InstallIntervalInstallIntervalStdAllD': -999999,
        'smsFinanceRepayRemindTimeIntervalStdAllD': -999999,
        'smsAllPayOutMessageDaysNuniqueAllD': -999999,
        'smsAllRepayRemindTimeIntervalStd14D': -999999,
        'smsAllAllMoneyMax7D': -999999,
        'smsAllOverdueTimeIntervalStdAllD': -999999,
        'smsAllPayInMsgNuniqueAllD': -999999,
        'smsAllLoanSuccessTimeIntervalStdAllD': -999999,
        'smsAllFinanceTimeIntervalMax14D': -999999,
        'appAllFuzzyLoanInstallIntervalInstallIntervalMedianAllD': -999999,
        'appIsSystembad2InstallIntervalInstallIntervalStdAllD': -999999,
        'smsFinanceVerificationTimeIntervalMinAllD': -999999,
        'appAllFuzzyLoanInstallIntervalInstallIntervalMedian30D': -999999,
        'smsAllmsgPlatFinanceMoneyStd3D': -999999,
        'appAllbad2InstallIntervalInstallIntervalStd60D': -999999,
        'smsAllAllTimeIntervalMedianAllD': -999999,
        'smsFinanceRepayRemindTimeIntervalMin60D': -999999,
        'smsAllRepaySuccessTimeIntervalMin7D': -999999,
        'appIsSystemFuzzyLoanInstallIntervalInstallIntervalStd60D': -999999,
        'smsAllRepaySuccessTimeIntervalMinAllD': -999999,
        'smsAllAllMsgNuniqueAllD': -999999,
        'smsAllVerificationTimeIntervalMedian60D': -999999,
    }
    print(get_user_model_score_main(features))
